/*
 * @Author: luoqi
 * @Date: 2022-03-27 15:09:12
 * @LastEditors: luoqi
 * @LastEditTime: 2022-04-30 10:01:30
 * @Description: 
 */
import React, { useState,useEffect } from 'react';
import { Form, Input, Button, Select, Space, Card, Table, Popconfirm, message,Cascader  } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';

import {connect} from 'react-redux'
import {addTab,changeActive} from '../../store/tabAction'
import tabs from '../tabs'
import ReactDOM from 'react-dom'
import axios from '../../utils/axios'
import qs from 'qs'

import PubSub from 'pubsub-js'
const { Option } = Select;


const Disease = (props) => {
  let [pag, setPag] = useState({ defaultCurrent: 1, pageSize: 4, current: 1,total:20, showTotal: total => `共 ${total} 条`, onChange: changePage })
  let [data, setData] = useState([])
  let [form]=Form.useForm()
  //用于触发重新渲染页面
  let [num, setNum] = useState(0)
  //搜索或全部
  let [isAll,setIsAll]=useState(true)
  //修改疾病信息
  let [modifyDisease,setModifyDisease]=useState()
   //页数更改时
   function changePage(page, pageSize) {
    setPag({ ...pag, current: page, pageSize:pageSize })
  }

  //页面加载完毕调接口，页数更改时调接口
  useEffect(() => {
    if(isAll){
      axios({
      url: '/sickness/selectByClassify',
      method: 'post',
      data: qs.stringify({
        page: pag.current,
        size: pag.pageSize,
      })
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        ReactDOM.unstable_batchedUpdates(() => {
          setIsAll(true)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
        })
        
        if (num == 1) {
          setNum(0)
        }

      }
    })
    }else{
      form.submit()
    }
     //订阅
   let info=PubSub.subscribe('setNumDisease',(_,data)=>{
    setNum(data)
    //  console.log(data);
    })
    return () => {
      PubSub.unsubscribe(info)
    };
  }, [pag.current, num,isAll])
  const onFinish = (values) => {
    // console.log('Success:', values);
    axios({
      url: '/sickness/selectByClassify',
      method: 'post',
      data: qs.stringify({
        page: pag.current,
        size: pag.pageSize,
        partPid:values.type1&&values.type1[0],
        partId:values.type1&&values.type1[1],
        departmentPid:values.type2&&values.type2[0],
        departmentId:values.type2&&values.type2[1],
        name:values.name
      })
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        ReactDOM.unstable_batchedUpdates(() => {
          setIsAll(false)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
        })
        setNum(2)

      }else if(res.code=='5012'){
          //提示
          message.success('没有数据');
      }else if(res.code=='500'){
        //提示
        message.warning('查询失败');
      }
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }
  function handleChange(value) {
    console.log(`selected ${value}`);
  }
  function addTab(str){
    //点击的选项
    let key=str
    //如果标签不存在就添加一个
    if (!props.tabs.panes.find(i => i.key === key)) {
      console.log(tabs[key]);
      let tab=tabs[key]
      //添加到panes
      props.addTab(tab)
    }else{
      console.log('已经存在');
    }
    props.changeActive(key)
  }
  
  //删除疾病
  function confirm(obj) {
    // console.log(obj);
    axios({
      url: '/sickness/delete',
      method: 'post',
      data: qs.stringify({ ids: obj.id.toString() })
    }).then(res => {
      console.log(res);
      if (res.code == '200') {
        message.success('删除成功');
        let num1=num+1
        setNum(num1)
      }
    })
  }
  
  function cancel(e) {
    console.log(e);
    message.error('Click on No');
  }
  //部位分类级联
  function onChange1(value) {
    // console.log(value);
  }
   //科室分类级联
   function onChange2(value) {
    // console.log(value);
  }
  //修改疾病
  function publishDisease(obj){
    //发布
    PubSub.publish('modifyDisease',obj)
   addTab('modifyDisease');
  }
  const columns = [
    
    {
      title: '疾病图片',
      dataIndex: 'imgUrl',
      key: 'imgUrl',
      render: text => <img style={{height:'80px'}} src={text} alt="" />
    },
    {
      title: '疾病名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '疾病部位分类',
      dataIndex: 'classify1',
      key: 'classify1',
      render:(text,record)=>{
        return record.departmentPname+'、'+record.departmentName
      }
    },
    {
      title: '疾病科室分类',
      dataIndex: 'classify2',
      key: 'classify2',
      render:(text,record)=>{
        return record.partPname+'、'+record.partName
      }
    },
    
    {
      title: '浏览量',
      dataIndex: 'viewNum',
      key: 'viewNum',
    },
    
    {
      title: '收藏量',
      dataIndex: 'collectionNum',
      key: 'collectionNum',
    },
    {
      title: '疾病状态',
      dataIndex: 'status',
      key: 'status',
      render:text=>(text?'可用':'不可用')
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button type="primary" ghost onClick={()=>{publishDisease(record);setTimeout(()=>{
            publishDisease(record)
          },1000) }}>修改</Button>
          <Popconfirm
            title="确定要删除该疾病吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" ghost>删除</Button>
          </Popconfirm>
          
          
        </Space>
      ),
    },
  ];
  //处理分类树
  let o1=[],o2=[];
  o1=props.types.partTree
  o2=props.types.departmentTree
  function changeTree(obj){
    obj.forEach((item)=>{
      item.value=item['id'];
      item.label=item['name'];
      item.children&&changeTree(item.children)
    })
  }
  changeTree(o1)
  changeTree(o2)


  return (
    <div>
      <Form
        name="basic"
        form={form}
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 14,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Space>
          <Form.Item
            label="疾病名称"
            name="name"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="部位分类"
            name="type1"
            style={{width:'250px'}}
          >
            <Cascader  options={o1} onChange={onChange1} placeholder="请选择" />
          </Form.Item>
          <Form.Item
            label="科室分类"
            name="type2"
            style={{width:'250px'}}
          >
            <Cascader  options={o2} onChange={onChange2} placeholder="请选择" />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType='submit' icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="success" icon={<PlusOutlined />} onClick={()=>addTab('addDisease')}>
              添加
            </Button>
          </Form.Item>
        </Space>
      </Form>
      <Table columns={columns} dataSource={data} pagination={pag} />
    </div>
  );
}

export default connect(
  state=>({tabs:state.tabs,types:state.types}),{addTab,changeActive}
)(Disease);

